package org.javaweb.cms_web.controller;

import com.mysql.cj.util.StringUtils;
import org.javaweb.cms_web.model.*;
import org.javaweb.cms_web.model.Enum.ContentStatus;
import org.javaweb.cms_web.model.Enum.PermissionTypes;
import org.javaweb.cms_web.model.Enum.RoleType;
import org.javaweb.cms_web.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/superAdmin")
public class SuperAdminController {

    @Autowired
    private UserService userService;
    @Resource
    private TeamService teamService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private AchievementService achievementService;
    @Autowired
    private ArticleManagementService articleService;
    @Autowired
    private ArticleManagementService articleManagementService;

    // 1. 用户管理
    // 显示团队管理员列表
    @GetMapping("/users")
    public String listTeamAdmins(Model model) {
        model.addAttribute("admins", userService.getAllTeamAdmins());
        model.addAttribute("teams", teamService.getAllTeams());
        return "superAdmin/user_management";
    }

    // 显示创建团队管理员的表单
    @GetMapping("/users/create")
    public String showCreateAdminForm(Model model) {
        //用来传参给后端
        model.addAttribute("user", new User());
        model.addAttribute("teams", teamService.getAllTeams());
        return "superAdmin/create_admin";
    }

    // 处理创建团队管理员
    @PostMapping("/users/create")
    public String createAdmin(@ModelAttribute User user, RedirectAttributes redirectAttributes) {
        userService.createTeamAdmin(user);
        redirectAttributes.addFlashAttribute("message", "团队管理员创建成功！");
        return "redirect:/superAdmin/users";
    }

    // 显示编辑团队管理员的表单
    @GetMapping("/users/edit/{id}")
    public String showEditAdminForm(@PathVariable("id") Integer id, Model model, RedirectAttributes redirectAttributes) {
        User user = userService.findUserById(id);
        if (user != null && user.getRoleType() == RoleType.TEAM_ADMIN.getCode()) {
            model.addAttribute("user", user);
            // 添加团队列表以供选择
            model.addAttribute("teams", teamService.getAllTeams());
            return "superAdmin/edit_admin";
        } else {
            redirectAttributes.addFlashAttribute("error", "团队管理员不存在！");
            return "redirect:/superAdmin/users";
        }
    }

    // 处理编辑团队管理员
    @PostMapping("/users/edit")
    public String editAdmin(@ModelAttribute User user, RedirectAttributes redirectAttributes) {
        if (user != null) {
            if (StringUtils.isNullOrEmpty(user.getPassword())) {
                User userById = userService.findUserById(user.getUserId());
                user.setPassword(userById.getPassword());
            }
            userService.updateUser(user);
            redirectAttributes.addFlashAttribute("message", "团队管理员更新成功！");
        } else {
            redirectAttributes.addFlashAttribute("error", "团队管理员不存在！");
        }
        return "redirect:/superAdmin/users";
    }

    // 删除团队管理员
    @GetMapping("/users/delete/{id}")
    public String deleteAdmin(@PathVariable("id") Integer id, RedirectAttributes redirectAttributes) {
        User user = userService.findUserById(id);
        if (user != null && user.getRoleType() == RoleType.TEAM_ADMIN.getCode()) {
            userService.deleteUserById(id);
            redirectAttributes.addFlashAttribute("message", "团队管理员删除成功！");
        } else {
            redirectAttributes.addFlashAttribute("error", "团队管理员不存在！");
        }
        return "redirect:/superAdmin/users";
    }


    @GetMapping("/permissions/setup")
    public String setupPermissions(Model model) {
        // 获取所有的权限类型
        model.addAttribute("permissionTypes", PermissionTypes.values());
        return "superAdmin/setup_permissions";
    }

    // 为特定团队管理员设置权限模板
    @PostMapping("/permissions/setup")
    public String assignPermissions(int userId, int[] permissionTypes, RedirectAttributes redirectAttributes) {
        // 清空当前权限，重新分配权限
        List<Integer> list = new ArrayList<>();
        for (int permissionType : permissionTypes) {
            list.add(permissionType);
        }
        permissionService.setPermissionsForUser(userId, list);
        redirectAttributes.addFlashAttribute("message", "权限模板设置成功！");
        return "redirect:/superAdmin/users";
    }

    @GetMapping("/users/{userId}/modifyPermissions")
    public String modifyPermissions(@PathVariable int userId, Model model) {
        // 获取该用户的基本信息
        User user = userService.findUserById(userId);

        // 获取该用户的权限
        List<UserPermission> userPermissions = permissionService.getPermissionsByUserId(userId);

        // 获取用户权限的类型ID
        List<Integer> userPermissionValues = userPermissions.stream()
                .map(UserPermission::getPermissionType)
                .collect(Collectors.toList());

        // 获取所有权限类型
        List<PermissionTypes> allPermissions = Arrays.asList(PermissionTypes.values());

        // 将数据传递给视图
        model.addAttribute("user", user);
        model.addAttribute("userPermissions", userPermissionValues);  // 权限ID列表
        model.addAttribute("allPermissions", allPermissions);  // 所有权限列表
        return "superAdmin/modify_permissions";
    }

    // 修改特定管理员权限（POST请求）
    @PostMapping("/users/{userId}/modifyPermissions")
    public String saveModifiedPermissions(@PathVariable int userId,
                                          @RequestParam(required = false) List<Integer> permissionTypes,
                                          RedirectAttributes redirectAttributes) {
        // 更新该管理员的权限
        permissionService.setPermissionsForUser(userId,
                permissionTypes != null ? permissionTypes : new ArrayList<>());

        // 设置操作成功提示信息
        redirectAttributes.addFlashAttribute("message", "权限修改成功！");

        // 重定向回权限管理页面
        return "redirect:/superAdmin/users/" + userId + "/modifyPermissions";
    }

    // 获取所有管理员及其权限
    @GetMapping("/permissions/management")
    public String getPermissionsManagementPage(Model model) {
        // 获取所有团队管理员
        List<User> admins = userService.getAllTeamAdmins();

        // 获取每个管理员的权限
        List<UserPermission> permissions = new ArrayList<>();
        for (User admin : admins) {
            permissions.addAll(permissionService.getPermissionsByUserId(admin.getUserId()));
        }
        model.addAttribute("permissions", permissions);
        model.addAttribute("admins", admins);
        return "superAdmin/permissionManagement";
    }


    // 查看所有待审核的科研成果
    @GetMapping("/achievementReview")
    public String showAchievementReviewPage(Model model) {
        List<Achievement> achievements = achievementService.getAllAchievements();
        model.addAttribute("achievements", achievements);
        return "superAdmin/achievementReview";
    }

    // 查看所有待审核的文章
    @GetMapping("/articleReview")
    public String showArticleReviewPage(Model model) {
        List<ArticleDTO> articles = articleService.getAllArticles();
        model.addAttribute("articles", articles);
        return "superAdmin/articleReview";
    }

    //预览科研成果
    @GetMapping("/achievementReview/{id}")
    public String previewAchievement(@PathVariable("id") Integer achievementId, Model model) {
        Achievement achievement = achievementService.getAchievementById(achievementId);
        String url = articleManagementService.prepareUrl(achievement.getAttachmentLink());
        achievement.setAttachmentLink(url);
        model.addAttribute("achievement", achievement);
        return "superAdmin/achievementPreview";
    }

    //预览文章
    @GetMapping("/articleReview/{id}")
    public String previewArticle(@PathVariable("id") Integer articleId, Model model) {
        ArticleDTO article = articleService.getArticleById(articleId);
        String url = articleManagementService.prepareUrl(article.getAttachmentLink());
        article.setAttachmentLink(url);
        model.addAttribute("article", article);
        return "superAdmin/articlePreview";
    }

    // 审核科研成果
    @PostMapping("/achievementReview/{id}")
    public String reviewAchievement(@PathVariable("id") Integer achievementId,
                                    @RequestParam("status") Integer status,
                                    RedirectAttributes redirectAttributes) {
        boolean success = achievementService.updateStatus(achievementId, status);
        if (success) {
            redirectAttributes.addFlashAttribute("message", "审核成功！");
        } else {
            redirectAttributes.addFlashAttribute("error", "审核失败！");
        }
        if (status == ContentStatus.NOT_PASSED.getCode()) {
            return "redirect:/superAdmin/achievementReview/" + achievementId + "/reject";
        }
        return "redirect:/superAdmin/achievementReview";
    }

    //科研成果拒绝页面
    @GetMapping("/achievementReview/{id}/reject")
    public String showAchievementRejectPage(@PathVariable("id") Integer achievementId, Model model) {
        Achievement achievement = achievementService.getAchievementById(achievementId);
        model.addAttribute("achievement", achievement);
        return "superAdmin/achievementRejectReason";
    }

    //文章拒绝页面
    @GetMapping("/articleReview/{id}/reject")
    public String showArticleRejectPage(@PathVariable("id") Integer articleId, Model model) {
        ArticleDTO article = articleService.getArticleById(articleId);
        model.addAttribute("article", article);
        return "superAdmin/articleRejectReason";
    }

    //科研成果拒绝理由
    @PostMapping("/achievementReview/{id}/reject")
    public String rejectAchievement(@PathVariable("id") Integer achievementId,
                                    @RequestParam("rejectReason") String rejectReason,
                                    RedirectAttributes redirectAttributes) {
        boolean success = achievementService.updateRejectReason(achievementId, rejectReason);
        if (success) {
            redirectAttributes.addFlashAttribute("message", "拒绝理由更新成功！");
        } else {
            redirectAttributes.addFlashAttribute("error", "拒绝理由更新失败！");
        }
        return "redirect:/superAdmin/achievementReview";
    }

    // 审核文章
    @PostMapping("/articleReview/{id}")
    public String reviewArticle(@PathVariable("id") Integer articleId,
                                @RequestParam("status") Integer status,
                                RedirectAttributes redirectAttributes) {
        boolean success = articleService.updateStatus(articleId, status);
        if (success) {
            redirectAttributes.addFlashAttribute("message", "审核成功！");
        } else {
            redirectAttributes.addFlashAttribute("error", "审核失败！");
        }
        if (status == ContentStatus.NOT_PASSED.getCode()) {
            return "redirect:/superAdmin/articleReview/" + articleId + "/reject";
        }
        return "redirect:/superAdmin/articleReview";
    }

    //文章拒绝理由
    @PostMapping("/articleReview/{id}/reject")
    public String rejectArticle(@PathVariable("id") Integer articleId,
                                @RequestParam("rejectReason") String rejectReason,
                                RedirectAttributes redirectAttributes) {
        boolean success = articleService.updateRejectReason(articleId, rejectReason);
        if (success) {
            redirectAttributes.addFlashAttribute("message", "拒绝理由更新成功！");
        } else {
            redirectAttributes.addFlashAttribute("error", "拒绝理由更新失败！");
        }
        return "redirect:/superAdmin/articleReview";
    }
}